<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <!--        <el-button type="primary" icon="el-icon-delete" @click="delAllSelection" style="width: 110px">批量删除</el-button>-->
        <el-input v-model="search" placeholder="输入内容" class="handle-input mr10" clearable></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addSelection" style="width: 150px;float: right">添加新模板  </el-button>
      </div>
      <el-table :data="pagedData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="序号" width="55" align="center"></el-table-column>
        <el-table-column prop="kind1" label="一级分类" width="100" align="center"></el-table-column>
        <el-table-column prop="kind2" label="二级分类" width="100" align="center"></el-table-column>
        <el-table-column prop="content" label="模板填写内容"></el-table-column>
        <el-table-column prop="note" label="注释" width="500"></el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用'? 'success': scope.row.status === '停用'? 'danger': ''">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <div><el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button></div>
            <!--            <div><el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button></div>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination :total="total" :current-page="currentPage" :page-size="currentPageSize" :page-sizes="[2, 3, 5]"
                       layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChange" @current-change="pageChange">
        </el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible" width="50%">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="一级分类:" prop="kind1" width="70px">
          <el-input v-model="form.kind1" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="二级分类:" prop="kind2">
          <el-input v-model="form.kind2" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="模板填写内容:" prop="content">
          <el-input type="textarea" v-model="form.content" :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="注释:" prop="note">
          <el-input type="textarea" v-model="form.note" :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="状态:" align="left" width="120">
          <el-radio v-model="form.status" label="启用" style="margin-left: 10px">启用</el-radio>
          <el-radio v-model="form.status" label="停用">停用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
      </template>
    </el-dialog>

    <!--添加弹出框 -->
    <el-dialog title="添加新模板" v-model="addVisible" width="50%" >
      <el-form ref="form1" :model="form1" label-width="150px" :rules="form1Rules">
        <el-form-item label="一级分类 / 二级分类:" prop="kind">
          <el-cascader :options="options" v-model="form1.oldKind" style="width: 70%">
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
          <el-button type="primary" icon="el-icon-plus" style="margin-left: 10px" @click="showNewKindForm">添加新分类</el-button>
        </el-form-item>
        <el-form-item label="模板内容:" prop="content">
          <el-input type="textarea" v-model="form1.content" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="注释:" prop="note">
          <el-input type="textarea" v-model="form1.note" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <!--          <el-switch style="display: block; margin-top: 10px" v-model="form1.status"-->
          <!--                     active-color="#13ce66" inactive-color="#ff4949"-->
          <!--                     active-text="启用" inactive-text="停用">-->
          <!--          </el-switch>-->
          <el-radio v-model="form1.status" label="启用" style="margin-left: 10px">启用</el-radio>
          <el-radio v-model="form1.status" label="停用">停用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveAdd(form1)">确 定</el-button>
                </span>
      </template>
    </el-dialog>

    <!--添加新模板-->
    <el-dialog title="添加新模板分类" v-model="dialogFormVisible" width="30%" top="10%">
      <el-form :model="kindForm">
        <el-form-item label="一级分类" :label-width="formLabelWidth">
          <!--          <el-input v-model="kindForm.kind1" autocomplete="off"></el-input>-->
          <el-select v-model="kindForm.kind1" filterable allow-create>
            <el-option v-for="item in kind1Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" :label-width="formLabelWidth">
          <el-input v-model="kindForm.kind2" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitKind">确 定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {templateData, templateDelete,templateAdd,AddNewKind, templateKind, templateEdit} from "../../api/api";
export default {
  data() {
    return {
      // newKindVisible: false,
      formLabelWidth: '80px',
      dialogFormVisible: false,
      options:[],
      search: "",
      currentPage: 1,
      currentPageSize: 2,
      total: null,
      tableData: [],
      pagedData:[],
      multipleSelection: [],
      editVisible: false,
      addVisible: false,
      pageTotal: 3,
      form: {},
      form1:{},
      kindForm:{},
      idx: -1,// 点击编辑时记录点击的id
      id: -1,
      kind1Arr: [],//存储所有一级分类数据
      kind1children: [],//存储所有一级分类下的二级分类数据
      kind1Options: [],// 存储所有一级分类的下拉框数据
      kindOptions:[],// 存储所有类别信息
      form1Rules:{
        oldKind: [{required: true, message: '请选择模板分类', trigger: 'blur'}],
        newKind: [{required: false, message: '', trigger: 'blur'}],
        content: [{required: true, message: '请输入模板内容', trigger: 'blur'}],
        note: [{required: true, message: '请输入注释', trigger: 'change'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}],
      }
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 触发添加新分类
    showNewKindForm() {
      this.dialogFormVisible = true
      // 获取所有一级分类选择框
      this.kind1Options = []
      this.kind1Arr.forEach((item) => {
        let y = {
          value: item,
          label: item
        }
        this.kind1Options.push(y)
      })
    },
    // “确定” 添加新分类
    submitKind() {
      // 添加新分类进入级联选择器
      // 首先判断一级分类是否是数据库中内容
      let flag = false
      let msg = {}
      this.kind1Arr.forEach((item) =>{
        if(item === this.kindForm.kind1){
          flag = true
        }
      })
      // 不是数据库中已有的，先把一级分类添加入数据库，再添加二级分类
      if (!flag) {
        msg = {
          sdMblbFlmc : this.kindForm.kind1,
          sdMblbYwlx: 1,
          sdMblbYjflName: this.kindForm.kind1
        }
        console.log('新添加的分类:', msg)
        AddNewKind(msg).then(res=>{
          console.log('res.data', res.data)
          this.$message.success('添加一级分类成功！')
          this.getKindMsg()
        })
      }
      msg = {
        sdMblbFlmc: this.kindForm.kind2,
        sdMblbYwlx: 1,
        sdMblbYjflName: this.kindForm.kind1,
        sdMblbEjflName: this.kindForm.kind2
      }
      AddNewKind(msg).then(res=>{
        console.log('res.data', res.data)
        this.$message.success('添加模板分类成功！')
        this.getKindMsg()
      })
      this.dialogFormVisible = false // 弹框消失
      this.kindForm = [] // 弹框默认值置空
      this.getKindMsg()
    },
    // 模糊搜索
    searchList() {
      if (this.tableData.length > 0){
        let pageData = this.tableData.filter((item) =>
            item.kind1.includes(this.search)||
            item.kind2.includes(this.search)||
            item.content.includes(this.search)||
            item.note.includes(this.search)
        )
        this.pagedData = pageData.filter((item, index) =>
            index < this.currentPage * this.currentPageSize && index >= this.currentPageSize * (this.currentPage - 1)
        )
        this.total = pageData.length
      }
    },
    // 获取所有模板数据库数据
    getData() {
      templateData(1).then((res) =>{
        let i = 0;
        this.tableData = []
        res.data.data.forEach((item) => {
          let add = {
            id : ++i,
            delNum : item.sdYsgdmbId,
            kind1: item.sdYsgdmbYjflName,
            kind2: item.sdYsgdmbEjflName,
            content: item.sdYsgdmbContent,
            note: item.sdYsgdmbZs,
            status: item.sdYsgdmbZt === 1 ? '启用' : '停用'
          }
          this.tableData.push(add)
        })
        this.searchList()
      })
    },
    // 获取所有模板的类别信息
    getKindMsg() {
      this.options = []
      this.kind1Arr = []
      this.kindOptions = []
      templateKind().then((res) => {
        console.log('res.data.data', res.data.data)
        res.data.data.forEach((item)=>{
          if(item.sdMblbYwlx == 1 && item.sdMblbEjflName!=null){
            let dict = {
              kind1: item.sdMblbYjflName,
              kind2: item.sdMblbEjflName
            }
            this.kindOptions.push(dict)
            this.kind1Arr.push(item.sdMblbYjflName)
          }
        })
        this.kind1Arr = [...new Set(this.kind1Arr)]
        this.kind1Arr.forEach((item)=>{
          console.log('一级分类=:', item)
          this.kind1children = []
          this.kindOptions.forEach((arr)=>{
            if(item == arr.kind1){
              let child = {
                value: arr.kind2,
                label: arr.kind2,
              }
              this.kind1children.push(child)
            }
          })
          let y = {
            value: item,
            label: item,
            children: this.kind1children
          }
          this.options.push(y)
        })
      })
    },
    // 触发搜索按钮
    handleSearch() {
      this.currentPage = 1
      this.searchList();
    },
    // 删除操作
    // handleDelete(index) {
    //   const idx = (this.currentPage - 1) * this.currentPageSize  + index //需要删除的记录所在行（从0开始）
    //   const delNum = this.tableData[idx].delNum
    //   // 二次确认删除
    //   this.$confirm("确定要删除吗？", "提示", {
    //     type: "warning"
    //   }).then(() => {
    //     templateDelete(delNum).then((res) =>{
    //       console.log('信息：', res.data)
    //       if(res.data.status == 200){
    //         this.$message.success("删除成功");
    //         this.getData()
    //       }
    //     })
    //     // this.tableData.splice(idx, 1);
    //   }).catch(() => {
    //
    //   });
    // },
    // 多选操作
    // handleSelectionChange(val) {
    //   this.multipleSelection = val;
    // },
    // 批量删除
    // delAllSelection(index) {
    //   const len = this.multipleSelection.length
    //   if (len > 0) {
    //     this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       this.$message.success("删除成功！")
    //       this.tableData.splice(index, len);
    //     }).catch(() => {
    //       this.$message.info("已经取消删除")
    //     });
    //   } else{
    //     this.$message.error("未选中任何记录！");
    //   }
    //   this.multipleSelection = [];
    // },
    // 添加新模板
    // 添加新模板
    addSelection() {
      this.addVisible = true;
      this.getKindMsg()
    },
    // 保存添加模板
    saveAdd(form1) {
      this.$refs.form1.validate(valid => {
        if (valid){
          this.addVisible = false;
          let kind1 = ''
          let kind2 = ''
          console.log('this.options:', this.options)
          console.log('this.form1:', this.form1)
          if (this.options.length > 0){
            const y = {
              sdYsgdmbYjflName: this.form1.oldKind[0],
              sdYsgdmbEjflName: this.form1.oldKind[1],
              sdYsgdmbContent: this.form1.content,
              sdYsgdmbZs: this.form1.note,
              sdYsgdmbDglb:1,
              sdYsgdmbZt: this.form1.status == '启用' ? 1 : 0
            };
            console.log('添加的字段:',y)
            templateAdd(y).then((res) =>{
              console.log('添加信息：', res.data)
              if (res.data.data == 200) {
                this.$message.success('添加成功!')
                this.getData()
              }
            })
          }else{
            kind1 = this.form1.newKind.split('/')[0]
            kind2 = this.form1.newKind.split('/')[1]
            const y = {
              sdMblbFlmc: this.form1.oldKind[1],
              sdMblbYwlx: 1,
              sdYsgdmbYjflName: this.form1.oldKind[0],
              sdYsgdmbEjflName: this.form1.oldKind[1],
              sdYsgdmbContent: this.form1.content,
              sdYsgdmbZs: this.form1.note,
              sdYsgdmbZt: this.form1.status == '启用' ? 1 : 0
            };
          }
          console.log('kind1+kind2:', kind1 + "," + kind2)
          console.log('this.form1.status', this.form1.status)
          this.$refs.form1.resetFields()
          this.form1=[]
        }else{
          this.$message.info('添加失败!')
        }
      })
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.form = row;
      console.log('this.form', this.form)
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      console.log('编辑的字段：', this.form)
      let edit ={
        sdYsgdmbId: this.form.delNum,
        sdYsgdmbContent: this.form.content,
        sdYsgdmbZs: this.form.note,
        sdYsgdmbYjflName: this.form.kind1,
        sdYsgdmbEjflName: this.form.kind2,
        sdYsgdmbDglb: 1,
        sdYsgdmbZt: this.form.status == '启用' ? 1 : 0
      }
      templateEdit(edit).then((res) => {
        console.log('编辑api返回信息：', res.data)
        if (res.data.status == 200){
          this.editVisible = false;
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getData()
        }
      })
    },
    //当每页数量改变
    pageSizeChange(size) {
      this.currentPageSize = size
      this.searchList()
    },
    // 当当前页改变
    pageChange(page) {
      console.log(`当前页: ${page}`);
      this.currentPage = page
      this.searchList()
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
